<template>
  <div @click="handleSearchStaffClick">
    <div class="search-staff" v-if="data.length">
      <a-tag v-for="item in data" :key="item.id">{{ item.username }}</a-tag>
    </div>
    <a-input v-else placeholder="请选择应用负责人" />
  </div>
  <a-modal
    v-model:visible="tableOpen"
    title="应用负责人"
    width="70%"
    cancelText="取消"
    okText="确定"
    @ok="handleOk"
  >
    <div class="table-header-btn-zoom">
      <a-space>
        <a-button type="primary" danger @click="handleRemoveStaff"
          >删除</a-button
        >
        <a-button type="primary" @click="openAddStaffModal">添加</a-button>
      </a-space>
    </div>
    <a-table
      rowKey="id"
      :columns="columns"
      :data-source="data"
      :pagination="false"
      :row-selection="{
        selectedRowKeys: state.selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
    </a-table>
  </a-modal>
  <a-modal
    v-model:visible="addStaffOpen"
    title="添加应用负责人"
    cancelText="取消"
    okText="确定"
    @ok="handleAddStaff"
  >
    <a-form ref="formRef" :model="addStaffForm" :rules="rules">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="人员" name="users">
            <SearchStaffSelect
              v-if="addStaffOpen"
              @change="handleSearchStaffChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="类型" name="type">
            <a-select
              v-model:value="addStaffForm.type"
              :options="typeOptions"
              placeholder="请选择"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, defineProps, reactive, watch, defineEmits } from "vue";
import SearchStaffSelect from "./components/SearchStaffSelect.vue";
import { AppUserInfo } from "./type.d";
import { Key } from "ant-design-vue/lib/_util/type";

interface Props {
  appUserInfoList: AppUserInfo[];
}

const props = defineProps<Props>();

const tableOpen = ref<boolean>(false);

const data = ref(props.appUserInfoList || []);

const typeOptions = [
  { label: "应用IT负责人", value: "1" },
  { label: "应用业务负责人", value: "2" },
  { label: "运维负责人", value: "3" },
];

const columns = [
  {
    title: "姓名",
    dataIndex: "username",
    key: "username",
  },
  {
    title: "邮箱",
    dataIndex: "userMail",
    key: "userMail",
  },
  {
    title: "手机号",
    dataIndex: "userPhone",
    key: "userPhone",
  },
  {
    title: "类型",
    dataIndex: "type",
    key: "type",
    customRender: ({ text }) => {
      return typeOptions.find((option) => option.value === text)?.label;
    },
  },
];

const rules = {
  users: [
    { required: true, message: "请选择人员", trigger: "change", type: "array" },
  ],
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
};

const addStaffOpen = ref<boolean>(false);

const addStaffForm = reactive({
  type: undefined,
  users: [],
});

const handleSearchStaffClick = () => {
  tableOpen.value = true;
};

const openAddStaffModal = () => {
  addStaffForm.type = undefined;
  addStaffForm.users = [];
  addStaffOpen.value = true;
};

const formRef = ref();

const filterRepeatUsers = (users) => {
  const costomUsers = data.value.map((d) => {
    const { userId, type } = d;
    return `${userId}-${type}`;
  });
  return users.filter((user) => {
    return !costomUsers.includes(`${user.userId}-${user.type}`);
  });
};

const handleAddStaff = () => {
  formRef.value.validate().then(() => {
    const { type } = addStaffForm;
    const users = addStaffForm.users.map((user: any) => {
      return {
        ...user,
        type,
      };
    });
    const filteredUsers = filterRepeatUsers(users);
    data.value = [...data.value, ...filteredUsers];
    addStaffOpen.value = false;
  });
};

const handleSearchStaffChange = (users) => {
  addStaffForm.users = users;
};

const state = reactive<{
  selectedRowKeys: Key[];
}>({
  selectedRowKeys: [], // Check here to configure the default column
});

const onSelectChange = (selectedRowKeys: Key[]) => {
  state.selectedRowKeys = selectedRowKeys;
};

const handleRemoveStaff = () => {
  data.value = data.value.filter(
    (item) => !state.selectedRowKeys.includes(item.id)
  );
  state.selectedRowKeys = [];
};

const emit = defineEmits(["update:appUserInfoList"]);

const handleOk = () => {
  emit("update:appUserInfoList", data.value);
  tableOpen.value = false;
};
</script>

<style lang="less" scoped>
.search-staff {
  min-height: 32px;
  border: 1px solid #d9d9d9;
  padding: 4px 11px;
  cursor: pointer;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  border-radius: 6px;
}

.table-header-btn-zoom {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
